package net.qiqbframework.rabbitmq;

import net.qiqbframework.eventhandling.EventMessage;
import net.qiqbframework.eventhandling.distributing.EventChannel;
import net.qiqbframework.serialization.SerializedObject;
import net.qiqbframework.serialization.Serializer;
import org.springframework.amqp.rabbit.core.RabbitTemplate;

public class RabbitEventChannel implements EventChannel {

    private final RabbitTemplate rabbitTemplate;

    private final Serializer eventSerializer;

    public RabbitEventChannel(RabbitTemplate rabbitTemplate, Serializer eventSerializer) {
        this.rabbitTemplate = rabbitTemplate;
        this.eventSerializer = eventSerializer;
    }


    @Override
    public void sendEventMessage(EventMessage<?> eventMessage) {
        // 发送事件
        final SerializedObject<byte[]> metaData = eventMessage.serializeMetaData(eventSerializer, byte[].class);
        final SerializedObject<byte[]> payload = eventMessage.serializePayload(eventSerializer, byte[].class);
        RabbitEventMessage rabbitEventMessage = new RabbitEventMessage();
        // 元数据
        RabbitSerializedObject metaDataSerializedObject = new RabbitSerializedObject();
        metaDataSerializedObject.setContent(metaData.getData());
        metaDataSerializedObject.setClassName(metaData.getType().getName());
        metaDataSerializedObject.setRevision(metaData.getType().getRevision());
        rabbitEventMessage.setMetaData(metaDataSerializedObject);
        // 实体
        RabbitSerializedObject payloadSerializedObject = new RabbitSerializedObject();
        payloadSerializedObject.setContent(payload.getData());
        payloadSerializedObject.setClassName(payload.getType().getName());
        payloadSerializedObject.setRevision(payload.getType().getRevision());
        rabbitEventMessage.setPayload(payloadSerializedObject);
        rabbitTemplate.convertAndSend(RabbitBindingConfig.EXCHANGE_NAME, "", rabbitEventMessage);

    }
}
